package mysql

import (
	"context"
	"errors"
	"go.uber.org/zap"
	"golang-sgg-daijia/internal/model"
	"gorm.io/gorm"
)

type DriverInfoDao interface {
	GetByOpenid(ctx context.Context, openid string) (*model.DriverInfo, error)
	Create(ctx context.Context, driverInfo *model.DriverInfo) error
	GetByID(ctx context.Context, id int64) (*model.DriverInfo, error)
	Update(ctx context.Context, driverInfo *model.DriverInfo) error
	UpdateById(ctx context.Context, driverID int, fields map[string]interface{}) error
}

func NewDriverInfoDao(
	r *MysqlClient,
) DriverInfoDao {
	return &driverInfoDao{
		MysqlClient: r,
	}
}

type driverInfoDao struct {
	*MysqlClient
}

func (r *driverInfoDao) GetByOpenid(ctx context.Context, openid string) (*model.DriverInfo, error) {
	var driver model.DriverInfo
	if err := r.DB(ctx).Where("wx_open_id = ?", openid).First(&driver).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, nil
		}
		r.logger.WithContext(ctx).Error("driverInfoDao|GetByOpenid(", zap.Any("data", map[string]interface{}{
			"openid": openid,
		}), zap.Error(err))
		return nil, err
	}
	return &driver, nil
}

func (r *driverInfoDao) GetByID(ctx context.Context, id int64) (*model.DriverInfo, error) {
	var driver model.DriverInfo
	if err := r.DB(ctx).Where("id = ?", id).First(&driver).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, nil
		}
		r.logger.WithContext(ctx).Error("driverInfoDao|GetByID(", zap.Any("data", map[string]interface{}{
			"id": id,
		}), zap.Error(err))
		return nil, err
	}
	return &driver, nil
}

func (r *driverInfoDao) Create(ctx context.Context, driverInfo *model.DriverInfo) error {
	if err := r.DB(ctx).Create(driverInfo).Error; err != nil {
		r.logger.WithContext(ctx).Error("driverInfoDao|Create(", zap.Error(err))
		return err
	}
	return nil
}

func (r *driverInfoDao) UpdateById(ctx context.Context, driverID int, fields map[string]interface{}) error {
	if err := r.DB(ctx).Model(&model.DriverInfo{}).Where("id", driverID).Updates(&fields).Error; err != nil {
		r.logger.WithContext(ctx).Error("driverInfoDao|UpdateById(", zap.Any("data", map[string]interface{}{
			"driverID": driverID,
		}), zap.Error(err))
		return err
	}
	return nil
}

// Update DB.save有坑，需要写全driverInfo所有字段（包括update_time）
func (r *driverInfoDao) Update(ctx context.Context, driverInfo *model.DriverInfo) error {
	if err := r.DB(ctx).Save(driverInfo).Error; err != nil {
		r.logger.WithContext(ctx).Error("driverInfoDao|UpdateById(", zap.Any("data", map[string]interface{}{
			"driverInfo": *driverInfo,
		}), zap.Error(err))
		return err
	}
	return nil
}
